<template>
  <div class="Clue-container">
    <el-button type="primary" @click="addClue">录入线索</el-button>
    <el-button type="success" @click="importClueFromExcel">导入线索(Excel)</el-button>
    <el-button type="danger" @click="batchDel">批量删除</el-button>
    <el-table
      :data="clueList"
      style="width: 100%; margin-top: 12px"
      @selection-change="selectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="120" />
      <el-table-column label="负责人" width="120" show-overflow-tooltip>
        <template #default="scope">
          {{ scope.row.ownerDO?.name }}
        </template>
      </el-table-column>
      <el-table-column label="所属活动" width="120" show-overflow-tooltip>
        <template #default="scope">
          {{ scope.row.activityDO?.name }}
        </template>
      </el-table-column>
      <el-table-column prop="fullName" label="姓名" show-overflow-tooltip />
      <el-table-column label="称呼" show-overflow-tooltip>
        <template #default="scope">
          {{ scope.row.appellationDO?.typeValue }}
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机" show-overflow-tooltip />
      <el-table-column prop="weixin" label="微信" show-overflow-tooltip />
      <el-table-column label="是否贷款" show-overflow-tooltip>
        <template #default="scope">
          {{ scope.row.needLoanDO?.typeValue }}
        </template>
      </el-table-column>
      <el-table-column label="意向状态" show-overflow-tooltip>
        <template #default="scope">
          {{ scope.row.intentionStateDO?.typeValue }}
        </template>
      </el-table-column>
      <el-table-column label="意向产品" show-overflow-tooltip>
        <template #default="scope">
          {{ scope.row.intentionProductDO?.name }}
        </template>
      </el-table-column>
      <el-table-column label="线索状态" show-overflow-tooltip>
        <template #default="scope">
          {{ scope.row.stateDO?.typeValue }}
        </template>
      </el-table-column>
      <el-table-column label="线索来源" show-overflow-tooltip>
        <template #default="scope">
          {{ scope.row.sourceDO?.typeValue }}
        </template>
      </el-table-column>
      <el-table-column prop="nextContactTime" label="下次联系时间" show-overflow-tooltip />
      <el-table-column align="center" label="操作">
        <template #default="scope">
          <el-button
            type="primary"
            size="small"
            v-hasPermission="'clue:view'"
            @click="handleView(scope.row.id)"
          >
            详情
          </el-button>
          <el-button
            type="primary"
            size="small"
            v-hasPermission="'clue:edit'"
            @click="handleEdit(scope.row.id)"
          >
            编辑
          </el-button>
          <el-button
            size="small"
            type="danger"
            v-hasPermission="'clue:delete'"
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-if="total"
      background
      layout="prev, pager, next"
      :page-size="pageSize"
      :total="total"
      class="pagination"
      @change="pageChange"
      @prev-click="toPage"
      @next-click="toPage"
    />
    <el-dialog v-model="excelDialogVisible" title="导入线索Excel" width="55%" center>
      <el-upload
        ref="uploadRef"
        accept=".xls,.xlsx"
        :auto-upload="false"
        method="post"
        :http-request="uploadClueFile"
      >
        <template #trigger>
          <el-button type="primary">选择Excel文件</el-button>
        </template>
        仅支持后缀名为.xls或.xlsx的文件
        <template #tip>
          <div class="el-upload__tip">
            重要提示：
            <ul>
              <li>上传仅支持后缀名为.xls或.xlsx的文件</li>
              <li>给定Excel文件的第一行将视为字段名</li>
              <li>请确认您的文件大小不超过50M</li>
              <li>日期值以文本形式保存，必须符合yyyy-MM-dd格式；如：2025-01-01</li>
              <li>
                日期时间以文本形式保存，必须符合yyyy-MM-dd HH:mm:ss的格式；如：2025-01-01 16:59:59
              </li>
            </ul>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="excelDialogVisible = false">关 闭</el-button>
          <el-button type="primary" @click="submitUpload"> 导 入 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="Clue">
import httpRequest from '@/http/httpRequest'
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import type { UploadInstance } from 'element-plus'
import { UploadAjaxError } from 'element-plus/es/components/upload/src/ajax.mjs'
// type Props = {}
// defineProps<Props>()
// const emit = defineEmits([])
const router = useRouter()
// const route = useRoute()
const addClue = () => {}
const importClueFromExcel = () => {
  excelDialogVisible.value = true
}
const batchDel = () => {}
interface IClue {
  id: number | null
  ownerId: number | null
  activityId: number | null
  fullName: string | null
  appellation: number | null
  phone: string | null
  weixin: string | null
  qq: string | null
  email: string | null
  age: number | null
  job: string | null
  yearIncome: number | null
  address: string | null
  needLoan: number | null
  intentionState: number | null
  intentionProduct: number | null
  state: number | null
  source: number | null
  description: string | null
  nextContactTime: string | null
  createTime: string | null
  createBy: number | null
  editTime: string | null
  editBy: number | null
  ownerDO: IUser | null
  activityDO: IActivity | null
  appellationDO: IDicValue | null
  needLoanDO: IDicValue | null
  intentionStateDO: IDicValue | null
  intentionProductDO: IProduct | null
  stateDO: IDicValue | null
  sourceDO: IDicValue | null
}
interface IUser {
  id: number | null
  name: string | null
}
interface IActivity {
  id: number | null
  name: string | null
}
interface IProduct {
  id: number | null
  name: string | null
}
interface IDicValue {
  id: number | null
  typeValue: string | null
}
let clueList = ref<IClue[]>([])
const selectionChange = (newSelection: any[]) => {
  console.log('selectionChange', newSelection)
}
const handleView = (id: number) => {
  // router.push({
  //   path: '/home/market-activity-detail/' + id,
  // })
  httpRequest
    .doGet('/api/clue/' + id, {})
    .then((res) => {
      if (res.data.code == 200) {
      }
    })
    .catch((error) => {})
}
const handleEdit = (id: number) => {
  // router.push({
  //   path: '/home/market-activity-edit/' + id,
  // })
}
const handleDelete = (id: number) => {
  httpRequest
    .doDelete('/api/clue/' + id, {})
    .then((res) => {
      console.log(res.data.code == 200 ? '删除成功' : '删除失败')
    })
    .catch((error) => {})
}
let total = ref(0)
let pageSize = ref(10)
let pageChange = (currentPage: number, pageSize: number) => {
  getData(currentPage, pageSize)
}

let toPage = (currentPage: number) => {
  getData(currentPage, pageSize.value)
}

onMounted(() => {
  getData(1)
})
const getData = (currentPage: number, pageSize: number = 10) => {
  httpRequest
    .doGet('/api/clue', {
      currentPage: currentPage,
      pageSize: pageSize,
    })
    .then((res) => {
      if (res.data.code == 200) {
        clueList.value = res.data.data.list || []
        total.value = res.data.data.total
      }
    })
    .catch((error) => {})
}
let excelDialogVisible = ref(false)
const uploadRef = ref<UploadInstance>()
const submitUpload = () => {
  excelDialogVisible.value = false
  uploadRef.value?.submit()
}

interface UploadProgressEvent extends ProgressEvent {
  percent: number
}

interface UploadRequestOptions {
  action: string
  method: string
  data: Record<string, string | Blob | [string | Blob, string]>
  filename: string
  file: File
  headers: Headers | Record<string, string | number | null | undefined>
  onError: (evt: UploadAjaxError) => void
  onProgress: (evt: UploadProgressEvent) => void
  onSuccess: (response: any) => void
  withCredentials: boolean
}

const uploadClueFile = (options: UploadRequestOptions) => {
  console.log('uploadClueFile', options)
  let formData = new FormData()
  formData.append('file', options.file)
  httpRequest
    .doPost('/api/clue/importExcel', formData)
    .then((res) => {
      if (res.data.code == 200) {
        //清空已上传的文件
        uploadRef.value?.clearFiles()
      }
    })
    .catch((error) => {})
}
</script>

<style scoped lang="scss">
.Clue-container {
  min-height: 100%;
}
</style>
